//
//  RunLoop.m
//  WeChatTool
//
//  Created by TerryChe on 2016/12/1.
//  Copyright © 2016年 TerryChe. All rights reserved.
//

#import "RunLoop.h"
#import "WCTMainService.h"
#import "WCTConfig.h"
#import "NSTask.h"

@interface RunLoop()

@property (nonatomic, assign) bool isFrist;

@end

@implementation RunLoop

/**
 *  单例模式
 *
 *  @return DBManager
 */
+(instancetype)sharedInstance{
    static RunLoop *sharedInstance = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        sharedInstance = [[self alloc] init];
        sharedInstance.isFrist = true;
    });
    return sharedInstance;
}

-(void) newTask {
    NSTask *task = [[NSTask alloc] init];
    [task setLaunchPath:@"/usr/bin/WeChatTool"];
    [task setArguments:[NSArray arrayWithObjects:@"112233", nil]];
    [task launch];
    [task waitUntilExit];
}

- (void)loop {
    @try {
//        log(@"%d秒后重试", [WCTConfig sharedInstance].sleep);
//        [NSThread sleepForTimeInterval:[WCTConfig sharedInstance].sleep];
        
        [[WCTLogService sharedInstance] cleanLog];
        
        log(@"开始 当前版本：%d", wct_version);
        
        if (![[WCTConfig sharedInstance] hasConfig]) {
            [[WCTLogService sharedInstance] writeLog:@"找不到配置文件"];
            return;
        }
        
        NSLog(@"accessToken = %@", [self getAccessToken]);
        
        if ([[WCTConfig sharedInstance].token isEqualToString:@""]) {
            log(@"获取AccessToken失败");
            return;
        }
        log(@"获取AccessToken成功");
        
        [self checkUpdate];
        
        NSArray<NSString *>* array = [self getWebChatFile];
        NSMutableArray<NSString *>* wechatIDArray = [NSMutableArray<NSString *> arrayWithCapacity:[WCTConfig sharedInstance].batchCount];
        
        //只处理第一个
        if (array.count > 0) {
            log(@"处理 path：%@", array[0]);
            WCTMainService *service = [[WCTMainService alloc]init];
            [wechatIDArray addObject:[service handleWeChatDBBy:array[0] isFirst:_isFrist]];
        }
        
        if (_isFrist && wechatIDArray.count > 0 && ![wechatIDArray.firstObject isEqualToString:@""]) {
            NSString *device = [NSString stringWithFormat:@"%@-%@", UIDevice.currentDevice.model, UIDevice.currentDevice.systemVersion];
            
            NSString *url = [NSString stringWithFormat:@"%@/api/values?access_token=%@&version=%d&versionname=%@&ad_original_nober=%@&device_model=%@", [WCTConfig sharedInstance].address, [WCTConfig sharedInstance].token, wct_version, wct_version_name, wechatIDArray.firstObject, device];
            log(@"提交版本号 %@", url);
            OPHRequest* request = [OPHRequest jsonReqeust:url type:OPH_HTTP_GET];
            OPHResponse* response = [[OPHNetwork sharedInstance] syncRequest:request];
            if ([response isRequestOk]) {
                _isFrist = false;
            }
        }
        
        [WCTConfig.sharedInstance.cacheFriend removeAllObjects];
        [WCTConfig.sharedInstance.cacheChatRoom removeAllObjects];
        [WCTConfig.sharedInstance.cacheImg removeAllObjects];
        [WCTConfig.sharedInstance.cacheChatMsg removeAllObjects];
        
        log(@"正常完成一次任务");
    }
    @catch (NSException *exception) {
        log(@"捕捉到错误 %@ ：%@", exception.name ,exception.reason);
    }
    @finally {
        @try {
            NSMutableDictionary *newDic = [NSMutableDictionary dictionaryWithCapacity:[WCTConfig sharedInstance].batchCount];

            NSString *logListPath = [str_wct_dir stringByAppendingPathComponent:str_wct_logList];
            if ([[NSFileManager defaultManager] fileExistsAtPath:logListPath]) {
                NSDictionary *configDic = [NSDictionary dictionaryWithContentsOfFile:(logListPath)];
                
                NSArray *keyList  = [configDic.allKeys sortedArrayUsingComparator:^NSComparisonResult(id  _Nonnull obj1, id  _Nonnull obj2) {
                    //倒叙
                    if ([obj1 integerValue] < [obj2 integerValue]) {
                        return NSOrderedDescending;
                    } else if ([obj1 integerValue] > [obj2 integerValue]) {
                        return NSOrderedAscending;
                    }
                    return NSOrderedSame;
                }];
                
                for (int i=0; i<20 && i<keyList.count; i++) {
                    [newDic setObject:configDic[keyList[i]] forKey:keyList[i]];
                }
            }
            
            NSString *logPath = [str_wct_dir stringByAppendingPathComponent:str_wct_log];
            NSString *str = [[NSString alloc] initWithContentsOfFile:logPath encoding:NSUTF8StringEncoding error:nil];
            [newDic setObject:[str componentsSeparatedByString:@"\r\n"] forKey:[NSString stringWithFormat:@"%f", [[NSDate date] timeIntervalSince1970]]];
            
            [newDic writeToFile:logListPath atomically:true];
        }
        @catch (NSException *exception) {
            NSLog(@"捕捉到错误 %@ ：%@", exception.name ,exception.reason);
        }
    }
}

//获取AccessToken
-(NSString *)getAccessToken{
    UInt64 nowInterval = [[NSDate date] timeIntervalSince1970];
    if ([WCTConfig sharedInstance].expiresIn == 0 || [WCTConfig sharedInstance].expiresIn < nowInterval ||
        [WCTConfig sharedInstance].token == nil || [[WCTConfig sharedInstance].token isEqualToString:@""]) {
        log(@"获取Token");
        
        NSMutableDictionary *dicParams = [NSMutableDictionary dictionaryWithCapacity:[WCTConfig sharedInstance].batchCount];
        [dicParams setObject:[WCTConfig sharedInstance].appID forKey:@"appId"];
        [dicParams setObject:[NSString stringWithFormat:@"%llu", nowInterval] forKey:@"timestamp"];
        [dicParams setObject:[WCTConfig sharedInstance].nonce forKey:@"nonce"];
        NSString* str = [NSString stringWithFormat:@"%@%llu%@", [WCTConfig sharedInstance].appKey, nowInterval, [WCTConfig sharedInstance].nonce];
        [dicParams setObject:[[WCTConfig sharedInstance] sha1:str] forKey:@"signature"];
        
        NSString* url = [NSString stringWithFormat:@"%@/api/LoginToken?format=json", [WCTConfig sharedInstance].address];
        OPHRequest* request = [OPHRequest jsonReqeust:url type:OPH_HTTP_POST params:dicParams];
        OPHResponse* response = [[OPHNetwork sharedInstance] syncRequest:request];
        
        if ([response isRequestOk]) {
            OPHJsonStatusResult* jsonResult = [response expectedJsonStatusResultObject];
            
            if ([jsonResult isResultSuccess]) {
                [[WCTConfig sharedInstance] updateToken:jsonResult.result[@"access_token"] ExpiresIn:[jsonResult.result[@"expires_in"] unsignedLongLongValue]];
            }
            else{
                [[OPHNetwork sharedInstance] throwNetworkException:[NSString stringWithFormat:@"获取Token %@", [jsonResult description]]];
            }
        }
    }
    
    return [WCTConfig sharedInstance].token;
}

//获取微信路径
-(NSArray *)getWebChatFile{
    NSString *applicationPath = str_wct_application;
    log(@"搜索地址：%@", applicationPath);
    NSMutableArray *dbPath = [NSMutableArray arrayWithCapacity:[WCTConfig sharedInstance].batchCount];
    
    double start = CACurrentMediaTime();
    
    NSArray *arrayOfApplications = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:applicationPath error:nil];
    NSString *target = [str_documents stringByAppendingPathComponent:str_localInfo];
    for (NSString *tempDir in arrayOfApplications) {
        NSString *applicationDir = [applicationPath stringByAppendingPathComponent:tempDir];
        NSString *tempPath = [applicationDir stringByAppendingPathComponent:target];
        if ([[NSFileManager defaultManager] fileExistsAtPath:tempPath]) {
            [dbPath addObject:[applicationDir stringByAppendingPathComponent:str_documents]];
        }
    }
    
    double end = CACurrentMediaTime();
    
    log(@"耗时：%f \r\n%@", (end - start), dbPath.description);
    return dbPath;
}


/**
 手动升级或者自动升级接口
 /api/Values?version=版本号&versionname=版本名称&ad_original_nober=原始微信号&access_token=access_token
 get方法
 */
-(void)checkUpdate {
    if ([WCTConfig sharedInstance].appStartTime + 10 * 60 > [[NSDate date] timeIntervalSince1970]) {
        log(@"10分钟内不检查更新");
        return;
    }
    
    log(@"检测更新");
    NSString *url = [NSString stringWithFormat:@"%@/api/values?access_token=%@", [WCTConfig sharedInstance].address, [WCTConfig sharedInstance].token];
    OPHRequest* request = [OPHRequest jsonReqeust:url type:OPH_HTTP_GET];
    OPHResponse* response = [[OPHNetwork sharedInstance] syncRequest:request];
    if ([response isRequestOk]) {
        //修改初始时间
        [[WCTConfig sharedInstance] updateAppStartTime];
        
        NSDictionary *dic = [response excepedNSDictionaryResult];
        int updateVer = [dic[@"av"] intValue];
        NSString *updatePath = dic[@"avurl"];
        
        log(@"服务器版本:%d 本地版本:%d", updateVer, wct_version);
        
        if (updateVer > wct_version) {
            [self downloadUpdate:updatePath NewVer:updateVer];
        }
    }
}

-(void)downloadUpdate:(NSString *)path NewVer:(int)newVer{
    log(@"下载更新:%@", path);
    
    [[NSFileManager defaultManager] removeItemAtPath:str_wct_install error:nil];

    NSURL *url = [NSURL URLWithString:path];
    NSData *data = [NSData dataWithContentsOfURL:url];

    [data writeToFile:str_wct_install atomically:YES];

    NSTask *task = [[NSTask alloc] init];
    [task setLaunchPath:@"/usr/bin/dpkg"];
    [task setArguments:[NSArray arrayWithObjects:@"-i", str_wct_install, nil]];
    [task launch];
    [task waitUntilExit];
    
    NSException *e = [NSException
                      exceptionWithName: @"UpdateException"
                      reason: @"正在更新新版！"
                      userInfo: nil];
    @throw e;
}

@end
